import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { ValidationPipe, BadRequestException } from '@nestjs/common';
import { AppModule } from '@/app.module';
import { AllExceptionsFilter } from '@/filter/allExceptionsFilter';
import { SuccessResponse } from '@/interceptor/successResponse';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    abortOnError: false,
    logger: ['error', 'log', 'warn', 'debug']
  });
  //允许跨域请求
  app.enableCors();
  //管道校验
  app.useGlobalPipes(
    new ValidationPipe({
      enableDebugMessages: process.env.NODE_ENV === 'development',
      transform: true, // 自动转换类型
      whitelist: true, // 验证器将删除已验证（返回）对象的任何不使用任何验证装饰器的属性
      stopAtFirstError: true, // 返回第一条错误
      exceptionFactory: (errors) => {
        let message = 'Bad Request';
        const constraints = errors?.[0]?.constraints || {};
        Object.keys(constraints).forEach((key) => {
          message = constraints[key];
        });
        return new BadRequestException(message);
      }
    })
  );
  //异常过滤
  app.useGlobalFilters(new AllExceptionsFilter());
  //全局拦截器
  app.useGlobalInterceptors(new SuccessResponse());

  // 配置服务
  const configService = app.get(ConfigService);
  const http = configService.get<Config.Http>('http');

  await app.listen(http.port);
  console.info(`Server is running at: ${http.host}:${http.port}`);
}

bootstrap();
